#include "contiki.h"
#include "contiki-net.h"
#include "ip64/ip64.h"
#include "net/netstack.h"
#include "net/routing/routing.h"
#include "sys/autostart.h"

/*---------------------------------------------------------------------------*/
/* Log configuration */
#include "sys/log.h"
#define LOG_MODULE "ip64-router"
#define LOG_LEVEL LOG_LEVEL_MAIN

/*---------------------------------------------------------------------------*/
PROCESS(router_node_process, "Router node");
//AUTOSTART_PROCESSES(&router_node_process);
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(router_node_process, ev, data)
{
    PROCESS_BEGIN();

    static struct etimer et;

    /* Set us up as a RPL root node. */
    NETSTACK_ROUTING.root_start();

    /* Initialize the IP64 module so we'll start translating packets */
    ip64_init();

    /* Wait to get a DHCP address */
    etimer_set(&et, CLOCK_SECOND * 3);

    while (1)
    {
        PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));

        if (ip64_hostaddr_is_configured())
        {
            const uip_ip4addr_t *hostaddr = ip64_get_hostaddr();
            const uip_ip4addr_t *netmask = ip64_get_netmask();
            const uip_ip4addr_t *gwaddr = ip64_get_draddr();

            LOG_DBG("IPv4 DHCP address: %d.%d.%d.%d\n", hostaddr->u8[0],
                    hostaddr->u8[1],
                    hostaddr->u8[2],
                    hostaddr->u8[3]);
            LOG_DBG("Netmask : %d.%d.%d.%d\n", netmask->u8[0], netmask->u8[1],
                    netmask->u8[2], netmask->u8[3]);
            LOG_DBG("Gateway: %d.%d.%d.%d\n", gwaddr->u8[0], gwaddr->u8[1],
                    gwaddr->u8[2], gwaddr->u8[3]);
            break;
        }

        etimer_reset(&et);
    }

    /* ... and do nothing more. */
    while (1)
    {
        PROCESS_WAIT_EVENT();
    }

    PROCESS_END();
}
/*---------------------------------------------------------------------------*/
